package kr.co.medical.controller;

import java.security.Principal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;

import kr.co.medical.dao.DoctorDao;
import kr.co.medical.dao.MedicalDao;
import kr.co.medical.dao.NoticeDAO;
import kr.co.medical.dao.OfficeDao;
import kr.co.medical.dao.PatientDao;
import kr.co.medical.dto.Cheobang_waiting_list;
import kr.co.medical.dto.Doctor;
import kr.co.medical.dto.DoctorMajor;
import kr.co.medical.dto.Dose;
import kr.co.medical.dto.Jupsoo;
import kr.co.medical.dto.Master;
import kr.co.medical.dto.Notice;
import kr.co.medical.dto.Patient;
import kr.co.medical.dto.Radio_Info;
import kr.co.medical.dto.RowNumDTO;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

@Controller
public class PatientController {
	@Autowired
	private SqlSession sqlSessionTemplate;

	@RequestMapping(value = { "join.do" }, method = RequestMethod.GET)
	public String join() {
		return "patient.join";
	}

	@RequestMapping(value = { "join.do" }, method = RequestMethod.POST)
	public String join(Patient patient) throws Exception {
		// patientdao.insert(patient);
		// Md5 md5 = new Md5();
		// patient.setPassword(md5.getEncMD5(patient.getPassword()));
		PatientDao patientdao = sqlSessionTemplate.getMapper(PatientDao.class);
		patientdao.insert(patient);
		String user_id = patient.getUser_id();
		patientdao.insertRole(user_id);

		return "redirect:./index.do";
	}

	@RequestMapping(value = { "masterlogin.do" }, method = RequestMethod.POST)
	public ModelAndView masterlogin(String id, String password,
			ModelAndView mav, HttpSession session)
			throws ClassNotFoundException, SQLException {
		Master master;
		PatientDao patientdao = sqlSessionTemplate.getMapper(PatientDao.class);
		master = patientdao.getMaster(id, password);
		// System.out.println("master.getName : " + master.getName());
		// System.out.println(master.getId());
		if (master != null) {

			if (master.getStaff_code_id().equals("1")) {
				mav.setViewName("doctor.doctor");

				mav.addObject("doctor_id1", master.getId());
				mav.addObject("name1", master.getName());
				// System.out.println(master.getId());
				session.setAttribute("doctor_id2", master.getId());
				session.setAttribute("name2", master.getName());
				// System.out.println("hh : " +
				// session.getAttribute("doctor_id2"));
				String doctor_id = master.getId();
				DoctorDao doctordao = sqlSessionTemplate
						.getMapper(DoctorDao.class);
				List<Cheobang_waiting_list> list = doctordao.waitinglist(master
						.getId());
				mav.addObject("list", list);
				int count = doctordao.countlist(doctor_id);
				System.out.println(count);
				mav.addObject("count", count);
				List<Dose> doselist = doctordao.selectdose();
				mav.addObject("doselist", doselist);

				mav.addObject("doctor", master.getId());
				return mav;

			} else if (master.getStaff_code_id().equals("2")) {
				MedicalDao medicalDao = sqlSessionTemplate
						.getMapper(MedicalDao.class);
				List<Radio_Info> list = medicalDao.selectRadio();
				session.setAttribute("medical", master.getId());
				mav.setViewName("medical/m_waiting_list");
				mav.addObject("radiolist", list);

				return mav;

			} else if (master.getStaff_code_id().equals("3")) {
				mav.setViewName("office.patientinfo");
				// mav.addObject("office",master.getId());
				List<Patient> list = new ArrayList<Patient>();
				list = patientdao.selectPatient();
				mav.addObject("list", list);
				return mav;
			}
			return mav;
		} else {
			mav.setViewName("redirect:./loginform.do");
			return mav;
		}
	}

	@RequestMapping("myinfo.do")
	public ModelAndView myinfo(String user_id, ModelAndView mav)
			throws ClassNotFoundException, SQLException {
		PatientDao patientdao = sqlSessionTemplate.getMapper(PatientDao.class);
		Patient patient = patientdao.patientInfo(user_id);
		mav.addObject("patient", patient);
		mav.setViewName("patient.myinfo");
		return mav;
	}

	@RequestMapping("doctor.do")
	public String showdoctor(
			@RequestParam(value = "dept_id", required = true) String dept_id,
			Model model) {
		model.addAttribute("dept_id", dept_id);
		System.out.println(dept_id);
		return "patient.doctor";
	}

	@RequestMapping("loginform.do")
	public String loginform() {
		return "patient.loginform";
	}

	@RequestMapping(value = { "loginform.do" }, method = RequestMethod.POST)
	public ModelAndView login(String patient_id, String password,
			ModelAndView mav) throws Exception {

		Patient patient;

		PatientDao patientdao = sqlSessionTemplate.getMapper(PatientDao.class);
		// patient=patientdao.getPatient(patient_id,pwd);
		patient = patientdao.getPatient(patient_id, password);
		// System.out.println(patient.getUser_id());
		if (patient == null) {

			mav.setViewName("redirect:./loginform.do");

			return mav;
		} else {
			mav.addObject("patientok", patient);
			mav.setViewName("index.main");
			return mav;
		}

	}

	@RequestMapping("reservation.do")
	public ModelAndView reservation(ModelAndView mav, String user_id,
			Principal principal) throws ClassNotFoundException, SQLException {

		if (SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal().equals("anonymousUser")) {
			mav.setViewName("redirect:./loginform.do");
			return mav;
		} else {
			PatientDao patientDao = sqlSessionTemplate
					.getMapper(PatientDao.class);
			Patient reservation = patientDao.reservation(principal.getName());
			mav.addObject("reservation", reservation);
			mav.setViewName("patient.reservation");
			return mav;
		}
	}

	@RequestMapping(value = { "doctorProfile.do" }, produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public HashMap<String, Object> doctorProfile(String dept_id)
			throws ClassNotFoundException, SQLException {
		DoctorDao doctorDao = sqlSessionTemplate.getMapper(DoctorDao.class);
		System.out.println(dept_id);
		List<Doctor> list = doctorDao.doctorProfile(dept_id);
		HashMap<String, Object> dprofile = new HashMap<String, Object>();
		dprofile.put("doctorlist", list);
		System.out.println(dprofile);
		return dprofile;
	}

	@RequestMapping(value = { "doctorProfile2.do" }, produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public HashMap<String, Object> doctorProfile2(String doctor_id)
			throws ClassNotFoundException, SQLException {

		DoctorDao doctorDao = sqlSessionTemplate.getMapper(DoctorDao.class);
		System.out.println(doctor_id);
		List<DoctorMajor> list = doctorDao.doctorProfile2(doctor_id);
		HashMap<String, Object> dprofile2 = new HashMap<String, Object>();
		dprofile2.put("doctorlist2", list);
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i).getDETAIL_NAME());
		}
		return dprofile2;
	}

	@RequestMapping(value = { "doctorProfile3.do" }, produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public HashMap<String, Object> doctorProfile3(String doctor_id)
			throws ClassNotFoundException, SQLException {
		DoctorDao doctorDao = sqlSessionTemplate.getMapper(DoctorDao.class);
		System.out.println(doctor_id);
		List<DoctorMajor> list = doctorDao.doctorProfile3(doctor_id);
		HashMap<String, Object> dprofile3 = new HashMap<String, Object>();
		dprofile3.put("doctorlist3", list);
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i).getPHOTO());
		}
		return dprofile3;
	}

	@RequestMapping(value = { "doctorHistory.do" }, produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public HashMap<String, Object> doctorHistory(String doctor_id)
			throws ClassNotFoundException, SQLException {
		System.out.println("doctor_id : " + doctor_id);
		Doctor doctor = new Doctor();
		doctor.setDoctor_id(doctor_id);

		System.out.println("doctor.getDoctor_id() : " + doctor.getDoctor_id());
		DoctorDao doctorDao = sqlSessionTemplate.getMapper(DoctorDao.class);
		List<Doctor> list = new ArrayList<Doctor>();
		list = doctorDao.doctorHistory(doctor);
		System.out.println(list.size());
		HashMap<String, Object> doctorHistory = new HashMap<String, Object>();
		doctorHistory.put("doctorHistory", list);

		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.size());
			System.out.println(list.get(i).getStart_year());
			System.out.println(list.get(i).getEnd_year());
			System.out.println(list.get(i).getContent());
		}
		return doctorHistory;
	}

	@RequestMapping(value = { "doctorScheduleDate.do" }, produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public HashMap<String, Object> doctorScheduleDate(Doctor doctor)
			throws ClassNotFoundException, SQLException {
		DoctorDao doctorDao = sqlSessionTemplate.getMapper(DoctorDao.class);
		List<Doctor> list = new ArrayList<Doctor>();
		list = doctorDao.doctorScheduleDate(doctor);
		HashMap<String, Object> doctorScheduleDate = new HashMap<String, Object>();
		ArrayList<Object> enableDay = new ArrayList<Object>();
		for (int i = 0; i < list.size(); i++) {
			enableDay.add(list.get(i).getSdate());
			System.out.println(list.get(i).getSdate());
		}
		doctorScheduleDate.put("enableDay", enableDay);
		return doctorScheduleDate;
	}

	@RequestMapping(value = { "doctorScheduleTime.do" }, produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public HashMap<String, Object> doctorScheduleTime(Doctor doctor)
			throws ClassNotFoundException, SQLException {
		DoctorDao doctorDao = sqlSessionTemplate.getMapper(DoctorDao.class);
		List<Doctor> list = new ArrayList<Doctor>();
		list = doctorDao.doctorScheduleTime(doctor);
		HashMap<String, Object> doctorScheduleTime = new HashMap<String, Object>();
		ArrayList<Object> enableTime = new ArrayList<Object>();
		for (int i = 0; i < list.size(); i++) {
			enableTime.add(list.get(i).getRes_time());
			System.out.println(list.get(i).getRes_time());
		}
		doctorScheduleTime.put("enableTime", enableTime);
		return doctorScheduleTime;
	}

	@RequestMapping(value = { "doctorScheduleId.do" }, produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public HashMap<String, Object> doctorScheduleId(String doctor_id,
			String sdate, String res_time) throws ClassNotFoundException,
			SQLException {
		DoctorDao doctorDao = sqlSessionTemplate.getMapper(DoctorDao.class);
		List<Doctor> list = doctorDao.doctorScheduleId(doctor_id, sdate,
				res_time);
		HashMap<String, Object> doctorScheduleId = new HashMap<String, Object>();
		doctorScheduleId.put("doctorScheduleId", list);
		return doctorScheduleId;
	}

	@Transactional
	@RequestMapping(value = { "reserveOk.do" }, produces = "text/plain;charset=UTF-8")
	public String reserveOk(Jupsoo jupsoo) throws ClassNotFoundException,
			SQLException {
		String patient_id = jupsoo.getPatient_id();
		System.out.println("patient_id : " + patient_id);
		String schedule_id = jupsoo.getSchedule_id();
		OfficeDao officedao = sqlSessionTemplate.getMapper(OfficeDao.class);
		System.out.println("schedule_id : " + schedule_id);
		officedao.addreser_v(jupsoo);
		String visitant_id = officedao.visitant(patient_id);
		System.out.println("visitant_id : " + visitant_id);
		officedao.addreser_j(jupsoo);
		officedao.addwaiting(visitant_id);
		officedao.updateschedule(schedule_id);
		return "redirect:/index.do";
	}

	/*
	 * @RequestMapping("reservationok.do") public ModelAndView reserok(String
	 * user_id) throws ClassNotFoundException, SQLException { ModelAndView mav =
	 * new ModelAndView(new MappingJacksonJsonView()); PatientDao patientDao =
	 * sqlSessionTemplate.getMapper(PatientDao.class); List<Jupsoo> list = new
	 * ArrayList<Jupsoo>(); list = patientDao.selectRes(user_id);
	 * mav.addObject("reslist", list); mav.setViewName("patient.reservationok");
	 * return mav; }
	 * 
	 * @RequestMapping("reservationok2.do") public ModelAndView reserok2(String
	 * user_id) throws ClassNotFoundException, SQLException { ModelAndView mav =
	 * new ModelAndView(new MappingJacksonJsonView()); PatientDao patientDao =
	 * sqlSessionTemplate.getMapper(PatientDao.class); List<Jupsoo> list = new
	 * ArrayList<Jupsoo>(); list = patientDao.selectRes(user_id);
	 * mav.addObject("reslist", list);
	 * 
	 * return mav; }
	 */
	@RequestMapping("medicalceo.do")
	public String medicalceo() {
		return "patient.medicalceo";
	}

	@RequestMapping("gil.do")
	public String gil() {
		return "patient.gil";
	}

	@RequestMapping("checkId.json")
	@ResponseBody
	public String idCheck(String user_id) throws ClassNotFoundException,
			SQLException {
		String msg = "no";
		// System.out.println("user_id : " + user_id);
		PatientDao patientdao = sqlSessionTemplate.getMapper(PatientDao.class);
		Patient patient = patientdao.checkId(user_id);

		if (patient != null) {
			msg = "yes";
		}
		return msg;
	}

	@RequestMapping("modify.do")
	public String modifyInfo(String user_id, String password, String zipcode1,
			String zipcode2, String addr1, String addr2, String tel)
			throws ClassNotFoundException, SQLException {
		PatientDao patientdao = sqlSessionTemplate.getMapper(PatientDao.class);
		/*
		 * System.out.println("user_id : " + user_id + " / password : " +
		 * password + " / zipcode1 : " + zipcode1 + " / zipcode2 : " + zipcode2
		 * + " / addr1 : " + addr1 + " / addr2 : " + addr2 + " / tel : " + tel);
		 */
		int result = patientdao.updatePatient(user_id, password, zipcode1,
				zipcode2, addr1, addr2, tel);
		if (result == 0) {
			return "redirect:./myinfo.do?user_id" + user_id;
		}
		return "index.main";
	}

	@RequestMapping("cancelres.do")
	@ResponseBody
	public String cancelRes(String jupsoo_id) throws ClassNotFoundException,
			SQLException {
		System.out.println("delete : " + jupsoo_id);
		PatientDao patientDao = sqlSessionTemplate.getMapper(PatientDao.class);
		int num1 = patientDao.cancelwating(jupsoo_id);
		int num2 = patientDao.cancelRes(jupsoo_id);
		System.out.println("delete controller 탐 : ");
		return "patient.reservationok";
	}

	// ////////////////환자 예약 정보 페이징 처리하기/////////////////////
	// 게시판 전체 수
	public int getCount(String user_id) throws ClassNotFoundException,
			SQLException {
		System.out.println("patient getCount() 들어옴");
		int count = 0;
		PatientDao patientDao = sqlSessionTemplate.getMapper(PatientDao.class);
		count = patientDao.getCount(user_id);
		System.out.println("count 끝");
		return count;
	}

	// 페이지 사이즈, 페이지 그룹
	private final int PAGESIZE = 10;
	private final int PAGEGROUP = 5;

	@RequestMapping("reservationok.do")
	public ModelAndView getRes(String pageNumber, String user_id)
			throws ClassNotFoundException, SQLException {
		System.out.println("patient.reservationok.do");
		System.out.println("user_id : " + user_id + " / pageNumber : "
				+ pageNumber);
		ModelAndView mav = new ModelAndView(new MappingJacksonJsonView());
		List<Jupsoo> list = new ArrayList<Jupsoo>();
		PatientDao patientDao = sqlSessionTemplate.getMapper(PatientDao.class);
		// 현재 클릭 페이지
		int pageNum = 1;
		if (pageNumber != null)
			pageNum = Integer.parseInt(pageNumber);
		int totalCount = getCount(user_id);
		System.out.println("총 게시물수" + totalCount);

		// 페이지 갯수
		int totalPageCount = totalCount / PAGESIZE;
		// 0으로 나눠 떨어지지 않을경우 페이지 갯수를 +1한다.

		if (totalCount % PAGESIZE != 0) {
			totalPageCount++;
		}
		System.out.println("totalPageCount : " + totalPageCount);
		// startPage or endPage
		int startPage = (pageNum - 1) / PAGEGROUP * PAGEGROUP + 1;
		int endPage = startPage + (PAGEGROUP - 1);

		if (endPage > totalPageCount) {
			endPage = totalPageCount;
		}

		int endRow = PAGESIZE * pageNum;
		int startRow = endRow - PAGESIZE + 1;

		System.out.println(startRow);
		System.out.println(endRow);

		RowNumDTO rowNumDTO = new RowNumDTO();
		rowNumDTO.setStartRow(startRow);
		rowNumDTO.setEndRow(endRow);
		rowNumDTO.setPageNumber(pageNum);
		list = patientDao.selectRes(user_id, startRow, endRow);

		System.out.println("startRow : " + startRow);
		System.out.println("endRow : " + endRow);
		System.out.println("startPage : " + startPage);
		System.out.println("endPage : " + endPage);
		System.out.println("pageNum : " + pageNum);

		mav.addObject("boardCount", list.size());
		mav.addObject("totalPageCount", totalPageCount);
		mav.addObject("startPage", startPage);
		mav.addObject("endPage", endPage);
		mav.addObject("pageNumber", pageNum);
		mav.addObject("reslist", list);
		mav.setViewName("patient.reservationok");

		return mav;
	}

	@RequestMapping("reservationok2.do")
	public ModelAndView getRes2(String pageNumber, String user_id)
			throws ClassNotFoundException, SQLException {
		System.out.println("patient.reservationok2.do");
		System.out.println("user_id2 : " + user_id + " / pageNumber2 : "
				+ pageNumber);
		ModelAndView mav = new ModelAndView(new MappingJacksonJsonView());
		List<Jupsoo> list = new ArrayList<Jupsoo>();
		PatientDao patientDao = sqlSessionTemplate.getMapper(PatientDao.class);
		// 현재 클릭 페이지
		int pageNum = 1;
		if (pageNumber != null)
			pageNum = Integer.parseInt(pageNumber);
		int totalCount = getCount(user_id);
		System.out.println("총 게시물수" + totalCount);

		// 페이지 갯수
		int totalPageCount = totalCount / PAGESIZE;
		// 0으로 나눠 떨어지지 않을경우 페이지 갯수를 +1한다.

		if (totalCount % PAGESIZE != 0) {
			totalPageCount++;
		}
		System.out.println("totalPageCount2 : " + totalPageCount);
		// startPage or endPage
		int startPage = (pageNum - 1) / PAGEGROUP * PAGEGROUP + 1;
		int endPage = startPage + (PAGEGROUP - 1);

		if (endPage > totalPageCount) {
			endPage = totalPageCount;
		}

		int endRow = PAGESIZE * pageNum;
		int startRow = endRow - PAGESIZE + 1;

		System.out.println(startRow);
		System.out.println(endRow);

		RowNumDTO rowNumDTO = new RowNumDTO();
		rowNumDTO.setStartRow(startRow);
		rowNumDTO.setEndRow(endRow);
		rowNumDTO.setPageNumber(pageNum);
		list = patientDao.selectRes(user_id, startRow, endRow);

		System.out.println("startRow2 : " + startRow);
		System.out.println("endRow2 : " + endRow);
		System.out.println("startPage2 : " + startPage);
		System.out.println("endPage2 : " + endPage);

		mav.addObject("boardCount", list.size());
		mav.addObject("totalPageCount", totalPageCount);
		mav.addObject("startPage", startPage);
		mav.addObject("endPage", endPage);
		mav.addObject("pageNumber", pageNum);
		mav.addObject("reslist", list);

		return mav;
	}
	
	@RequestMapping("searchid.do")
	@ResponseBody
	public String searchId(String name, String jumin1, String jumin2) throws ClassNotFoundException, SQLException{
		System.out.println(name + " / " + jumin1 + " / " + jumin2);
		PatientDao patientdao = sqlSessionTemplate.getMapper(PatientDao.class);
		Patient patient = patientdao.searchId(name, jumin1, jumin2);
		String yourid = patient.getUser_id();
		System.out.println("찾은 아이디는 : " + yourid);
		
		return yourid;
	}
	
	@RequestMapping("searchpwd.do")
	@ResponseBody
	public String searchPwd(String user_id, String jumin1, String jumin2) throws ClassNotFoundException, SQLException{
		System.out.println(user_id + " / " + jumin1 + " / " + jumin2);
		PatientDao patientdao = sqlSessionTemplate.getMapper(PatientDao.class);
		Patient patient = patientdao.searchPwd(user_id, jumin1, jumin2);
		String yourpwd = patient.getPassword();
		System.out.println("찾은 비밀번호 : " + yourpwd);
		
		return yourpwd;
	}
}